package com.bjsxt.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.sound.midi.MetaEventListener;
import javax.xml.crypto.Data;
import java.util.Date;


@Component
public class AutoFillHandler implements MetaObjectHandler {
    /**
     * 新增数据时填充
     * 创建人
     * 创建时间
     * 最后更新时间
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getCurrentUserId();
        this.strictInsertFill(metaObject,"createBy", Long.class,userId);
        this.strictInsertFill(metaObject,"created", Date.class,new Date());
        this.strictInsertFill(metaObject,"lastUpdateTime", Date.class,new Date());

    }


    /**
     * 修改时的填充
     * 修改人
     * 修改时间
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
    Long userId = getCurrentUserId();
        this.strictUpdateFill(metaObject,"modifyBy", Long.class,userId);

        this.strictUpdateFill(metaObject,"lastUpdateTime", Date.class,new Date());

    }

    /**
     * 获取当前操作的用户对象
     * 从安全上下文获取
     * @return
     */
    private Long getCurrentUserId() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication!=null){
            String s = authentication.getPrincipal().toString();
            if("anonymousUser".equals(s)){
                return null;
            }
            return Long.valueOf(s);
        }
        return null;

    }

}
